import React, { useContext, useEffect, useState } from "react";
import {
  UserIdContext,
  UserContext,
  UserProContext,
  ThemeColorContext,
} from "../../App";
import "./login.css";
import { useSnackbar } from "notistack";
import getLocalUser from "../../api/getUser";
import useLogin from "../../query/useLogin";
import SaveIcon from "@mui/icons-material/Save";
import LoadingButton from "@mui/lab/LoadingButton";
import {
  AppBar,
  Box,
  Button,
  ButtonBase,
  createTheme,
  Dialog,
  DialogActions,
  DialogContent,
  DialogContentText,
  DialogTitle,
  Divider,
  IconButton,
  Link,
  List,
  ListItem,
  Paper,
  Slide,
  TextField,
  Toolbar,
  Typography,
} from "@mui/material";
import VerPng from "../../components/VerPng";
import useVrLogin from "../../query/useVrLogin";
import { useNavigate } from "react-router-dom";
import useReset from "../../query/useReset";
import { ThemeProvider } from "@emotion/react";
import { useMemo } from "react";
import MyDialog from "../../components/MyDialog";
import ThanksList from "./ThanksList";
import CloseIcon from "@mui/icons-material/Close";
export default function Index() {
  const user = useContext(UserContext); //角色context
  const stPro = useContext(UserIdContext);
  const [dialogOpen, setDialogOpen] = useState(false);
  const [theName, setTheName] = useState(1);
  const [loginUserName, setLoginUserName] = useState("");
  const [loginUserPsw, setLoginUserPsw] = useState("");
  const localUser = getLocalUser();
  const { enqueueSnackbar } = useSnackbar();
  const [vertifyCode, setVertifyCode] = useState("");
  const [verToken, setVerToken] = useState();
  const [lgType, setLgtype] = useState(false);
  const [changeVr, setChangeVr] = useState(false);
  const [email, setEmail] = useState("");
  const changeVrCode = (e) => {
    setVertifyCode(e.target.value);
  };
  const changeClass = () => {
    setLgtype(!lgType);
    if (theName === 0) setTheName(1);
    else setTheName(0);
  };
  const changeLgName = (e) => {
    setLoginUserName(e.target.value);
  };
  const changeLgPsw = (e) => {
    setLoginUserPsw(e.target.value);
  };
  const {
    isSuccess: VrSuccess,
    isError: VrIsError,
    mutate: vrMutate,
    data: VrData,
    isLoading: VrIsLoading,
  } = useVrLogin();
  const { data, isLoading, isSuccess, error, isError, mutate, reset } =
    useLogin();

  const {
    isSuccess: resetSuccess,
    isError: resetError,
    data: resetdata,
    mutate: resetMutate,
  } = useReset();
  useEffect(() => {
    if (resetSuccess) {
      enqueueSnackbar(resetdata.data.data, {
        variant: resetdata.data.code == 0 ? "success" : "warning",
      });
      if (resetdata.data.code == 0) {
        setLgtype(!lgType);
      }
    }
  }, [resetSuccess]);
  const userproContext = useContext(UserProContext);
  const Login = () => {
    //实现登录接口
    if (loginUserName === "" || loginUserPsw === "") {
      enqueueSnackbar("账号密码不能为空", { variant: "warning" });
      return;
    }
    if (vertifyCode == "") {
      enqueueSnackbar("请填写验证码", { variant: "warning" });
      return;
    }
    vrMutate({ vertifyCode, verToken });
  };
  useEffect(() => {
    if (VrSuccess) {
      if (VrData.data.message == "success") {
        if (!lgType) mutate({ userName: loginUserName, passwd: loginUserPsw });
        if (lgType) resetMutate({ userId: loginUserName, email: email });
      } else {
        enqueueSnackbar("验证码错误", { variant: "error" });
        setChangeVr(!changeVr);
        setVertifyCode("");
      }
    }
  }, [VrSuccess]);

  useEffect(() => {
    if (localUser != 0) {
      stPro.setUserId(localStorage.getItem("userId"));
    }
  });
  const navigate = useNavigate();
  const themeColor = useContext(ThemeColorContext);
  useEffect(() => {
    if (isError) {
      enqueueSnackbar("网络错误", { variant: "error" });
    }
    if (isSuccess) {
      //
      if (data.data.code === 0) {
        stPro.setUserId(loginUserName);
        localStorage.setItem("token", data.data.data.token);
        localStorage.setItem("userId", loginUserName);
        if (data.data.data.email != "") {
          localStorage.setItem("role", data.data.data.role);
          enqueueSnackbar("登录成功", { variant: "success" });

          themeColor.setThemeColor(data.data.data.role);
          localStorage.setItem("themecolor", data.data.data.role);

          user.setUser(data.data.data.role);
        } else {
          enqueueSnackbar("初次登陆请激活", { variant: "info" });
          navigate("/activation");
        }
        // proMutate();
      } else {
        setChangeVr(!changeVr);

        setVertifyCode("");
        enqueueSnackbar(data.data.message, { variant: "error" });
      }
      reset();
    }
  }, [isError, isSuccess]);

  const handleReset = () => {
    if (vertifyCode == "") {
      enqueueSnackbar("请填写验证码", { variant: "warning" });
      return;
    }
    if (email == "") {
      enqueueSnackbar("邮箱不能为空", { variant: "warning" });
      return;
    }
    if (loginUserName == "") {
      enqueueSnackbar("学号不能为空", { variant: "warning" });
      return;
    }
    vrMutate({ vertifyCode, verToken });
  };
  const innerTheme = useMemo(() =>
    createTheme({
      palette: {
        mode: "light",
      },
    })
  );
  const [open, setOpen] = useState(false);
  const handleClick = () => {
    navigate("/introduction");
  };
  return (
    <ThemeProvider theme={innerTheme}>
      <div className="mybody">
        <div
          className={
            theName === 0 ? "container right-panel-active" : "container"
          }
        >
          <div className="test">
            <div className="container__form container--signup">
              <div className="form" id="form1">
                <h2 className="form__title">忘记密码</h2>
                <TextField
                  size="small"
                  label="学号"
                  value={loginUserName}
                  onChange={(e) => {
                    setLoginUserName(e.target.value);
                  }}
                  type="text"
                  // placeholder="学号"
                  className="input"
                />
                <TextField
                  sx={{ marginTop: 2 }}
                  size="small"
                  value={email}
                  onChange={(e) => {
                    setEmail(e.target.value);
                  }}
                  label="邮箱"
                  type="email"
                  className="input"
                />
                <TextField
                  sx={{ marginTop: 2 }}
                  value={vertifyCode}
                  onChange={changeVrCode}
                  size="small"
                  label="验证码"
                  type="email"
                  className="input"
                />
                {lgType && <VerPng key={changeVr} s={setVerToken} />}

                <Button
                  sx={{ width: 120 }}
                  variant="contained"
                  onClick={handleReset}
                >
                  重置密码
                </Button>
              </div>
            </div>

            <div className="container__form container--signin">
              <div className="form" id="form2">
                <h2 className="form__title">登录</h2>
                <TextField
                  label="学号"
                  type="text"
                  size="small"
                  onChange={changeLgName}
                  // placeholder="学号"
                  value={loginUserName}
                  className="input"
                />
                <TextField
                  sx={{ marginTop: 2 }}
                  size="small"
                  type="password"
                  label="密码"
                  value={loginUserPsw}
                  onChange={changeLgPsw}
                  className="input"
                />
                <TextField
                  sx={{ marginTop: 2 }}
                  value={vertifyCode}
                  onChange={changeVrCode}
                  size="small"
                  label="验证码"
                  type="email"
                  className="input"
                />
                {/* <img src={imgUrl} style={{ width: 100 }}></img> */}
                {!lgType && <VerPng key={changeVr} s={setVerToken} />}

                {!isLoading && !VrIsLoading && (
                  // <button className="btn" >
                  //   登录
                  // </button>
                  <Button
                    sx={{ width: 120 }}
                    variant="contained"
                    onClick={Login}
                  >
                    登录
                  </Button>
                )}

                {(isLoading || VrIsLoading) && (
                  <LoadingButton
                    loading
                    // className="btn"
                    loadingPosition="start"
                    startIcon={<SaveIcon />}
                    variant="contained"
                    sx={{ color: "white" }}
                  >
                    正在登录
                  </LoadingButton>
                )}
              </div>
            </div>
            <div className="container__overlay">
              <div className="overlay">
                <div className="overlay__panel overlay--left">
                  <button className="btn" id="signIn" onClick={changeClass}>
                    登录
                  </button>
                </div>
                <div className="overlay__panel overlay--right">
                  <button className="btn" id="signUp" onClick={changeClass}>
                    忘记密码
                  </button>
                </div>
              </div>
            </div>
          </div>
        </div>
        <div>
          <Box sx={{ display: "flex", flexDirection: "row" }}>
            <Button
              onClick={() => setDialogOpen(true)}
              variant="contained"
              color="secondary"
              sx={{ marginRight: 10 }}
            >
              关于我们
            </Button>
            <ThanksList setOpen={setOpen} />
          </Box>
          <MyDialog
            showCancel={false}
            open={dialogOpen}
            onClose={() => setDialogOpen(false)}
            title="个人页面"
          >
            <List>
              <ListItem
                sx={{
                  display: "flex",
                  flexDirection: "column",
                  justifyContent: "center",
                }}
              >
                <Link
                  sx={{ cursor: "pointer" }}
                  href="http://home.wxyww.top"
                  underline="none"
                  target="_blank"
                >
                  吴羲勇
                </Link>
              </ListItem>
              <Divider />
              <ListItem
                sx={{
                  display: "flex",
                  flexDirection: "column",
                  justifyContent: "center",
                }}
              >
                <Link
                  href="https://surui.vercel.app"
                  target="_blank"
                  sx={{ cursor: "pointer" }}
                  underline="none"
                >
                  郭苏睿
                </Link>
              </ListItem>
              <Divider />
              <ListItem
                sx={{
                  display: "flex",
                  flexDirection: "column",
                  justifyContent: "center",
                }}
              >
                <Link
                  href="https://xuinrz.github.io/pp/"
                  target="_blank"
                  sx={{ cursor: "pointer" }}
                  underline="none"
                >
                  许子璇
                </Link>
              </ListItem>
              <Divider />
              <ListItem
                sx={{
                  display: "flex",
                  flexDirection: "column",
                  justifyContent: "center",
                }}
              >
                <Link
                  sx={{ cursor: "pointer" }}
                  // onClick={handleClick}
                  href="/#/introduction"
                  underline="none"
                  target="_blank"
                >
                  王治松
                </Link>
              </ListItem>
              <Divider />
              <ListItem
                sx={{
                  display: "flex",
                  flexDirection: "column",
                  justifyContent: "center",
                }}
              >
                <Link sx={{ cursor: "pointer" }} underline="none">
                  吕俊安
                </Link>
              </ListItem>
            </List>
          </MyDialog>
        </div>
      </div>

      <MyDialog2
        showCancel={false}
        open={open}
        onClose={() => setOpen(false)}
        title="致谢"
      ></MyDialog2>
    </ThemeProvider>
  );
}
const Transition = React.forwardRef(function Transition(props, ref) {
  return <Slide direction="up" ref={ref} {...props} />;
});
const MyDialog2 = (props) => {
  const { title, children, onClose, open } = props;

  return (
    <Dialog
      open={open}
      onClose={onClose}
      fullScreen
      aria-labelledby="alert-dialog-title"
      aria-describedby="alert-dialog-description"
      TransitionComponent={Transition}
    >
      <AppBar
        sx={{
          backgroundColor: "rgb(255 255 255 / 40%)",
          backdropFilter: "blur(8px)",
        }}
      >
        <Toolbar
          sx={{
            display: "flex",
            justifyContent: "center",
          }}
        >
          <Typography color="black" variant="h4">
            致谢
          </Typography>
          <Box sx={{ position: "fixed", right: "10px" }}>
            <IconButton
              edge="start"
              color="default"
              onClick={onClose}
              aria-label="close"
            >
              <CloseIcon />
            </IconButton>
          </Box>
        </Toolbar>
      </AppBar>
      <DialogContent
        sx={{
          minWidth: 300,
          minHeight: 100,
          justifyContent: "center",
          display: "flex",
          // marginTop: 10,
        }}
      >
        <Box id="mybox" sx={{ height: 100, width: "70%" }}>
          <Box>
            <Box sx={{ height: 60 }}></Box>
            <Typography sx={{ lineHeight: 1.8 }}>
              {" "}
              <p>
                我们发布这篇文章用于感谢在本项目中提供帮助和想法的朋友们。在本次历时个月的课程设计开发过程中，名单中的朋友们从技术上为我们提供帮助，思想上提供指导，创意上启发灵感，带领我们不断深入某项技术、拓宽技术视野，并为本次课设的设计带来弥足珍重的新思想。在他们的指导下，我们致力于将“课程设计”打造为“产品”，试图摆脱“作业”和“考核”的禁锢，以自由的姿态探索技术和产品。
                以下是相应的名单（排名不分先后）：
              </p>
              <ul>
                <li>
                  <strong>可爱猫娘子涵</strong>
                  <br />
                  子涵哥哥为我们前端开发的技术选型和状态化的设计思路等方面提供许多建议，使得我们有机会在React技术栈下更深入挖掘技术的可能性。
                </li>
              </ul>
              <ul>
                <li>
                  <strong>彩虹小马居正</strong>
                  <br />
                  居正富裕且慷慨的向我们分享了许多后端开发的规范、思想和技术细节，与我们就CORS等问题进行了深入讨论，带领我们营造更良好的前后端合作关系。
                </li>
              </ul>
              <ul>
                <li>
                  <strong>篠原春奈</strong>
                  <br />
                  春奈酱与我们讨论了许多业务开发的内容，与我们共同研讨了i山大的后端代码，从中学习OpenFeign等技术的细节。
                </li>
              </ul>
              <ul>
                <li>
                  <strong>加钱居士孔站 </strong>
                  <br />
                  在孔站的点拨下，我们开始尝试深入注解、过滤器和拦截器以及LocalStorage机制，并在后期开发出一套便捷的工具包。
                </li>
              </ul>
              <ul>
                <li>
                  <strong>老人智炜 </strong>
                  <br />
                  智炜哥哥慷慨的分享了isdu-doc项目的源码，与我们就依赖管理和项目框架的构建问题进行了许多分享，这使得我们具有了更高层次的抽象思想和架构能力。
                </li>
              </ul>
              <ul>
                <li>
                  <strong>张晖不是张辉 </strong>
                  <br />
                  在产品站长的指（pi）点（pan）中，我们对项目从产品角度进行了风格统一和设计，机缘巧合下选择可爱的Capoo作为主题，整个项目因此更有价值和灵魂。
                </li>
              </ul>
              <ul>
                <li>
                  <strong>劝学阿姨 </strong>
                  <br />
                  阿姨为我们项目的推进作出弥足珍贵的贡献，感谢阿姨每天坚持不懈的push，这个项目才没有中途烂尾。
                </li>
              </ul>
              <ul>
                <li>
                  <strong>wngg </strong>
                  <br />
                  尽管wngg的职责并不在前端/后端，但wngg的分享为我们就前端技术栈-Flutter的横向比较带来很大启发，并且分享了他宝贵的开发经验。
                </li>
              </ul>
              <ul>
                <li>
                  <strong>lkp </strong>
                  <br />
                  lkp作为主要的测试用户出现在系统的许多角落，我们很感谢lkp献出自己的名誉权供我们使用。
                </li>
              </ul>
              <ul>
                <li>
                  <strong>懒人沙发和行军床 </strong>
                  <br />
                  感谢办公室里的懒人沙发和行军床，睡起来真的很舒服。
                </li>
              </ul>
            </Typography>
            <Box sx={{ height: "300px" }}></Box>
          </Box>
          {/* <ul id="comment2"></ul> */}
          {/* </div> */}
        </Box>
      </DialogContent>
    </Dialog>
  );
};
